#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'

from PySide import QtGui, QtCore
import os
import ctypes
from .baseui.noborderwidget import NoBorderWidget
from .title_bar_widget import TitleBarWidget
from .user_widget import UserWidget
# from searchwidget import SearchWidget
from .tab_view_widget import TabViewWidget
from .app_bar_widget import AppBarWidget
from .skin_widget import SkinWidget
from .parse_yaml import parse_yaml_file
from . import local_data
from .pyuic.desktop_widget import Ui_desktop_widget
from .get_path import get_folder_path

class DesktopWidget(NoBorderWidget):
    def __init__(self, parent=None):
        super(DesktopWidget, self).__init__(parent)

        self._ui = Ui_desktop_widget()
        self._ui.setupUi(self)
        self.history_data = {}
        self._project = False
        self.setMaximumWidth(600)
        self.setWindowTitle('Versatile')
        self.skin_data = {'image':':/icons/default_skin.png', 'color':QtGui.QColor(172, 215, 78)}
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(':/icons/ver_logo.ico'), QtGui.QIcon.Normal, QtGui.QIcon.Off)

        self.setWindowIcon(icon)
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")
        self.title_bar_widget = TitleBarWidget(self)
        self.user_widget = UserWidget(self)

        #self.search_widget = SearchWidget(self)
        self.tab_view_widget = TabViewWidget(self)
        self.app_bar_widget = AppBarWidget()

        self._ui.top_layout.addWidget(self.title_bar_widget)
        self._ui.top_layout.addWidget(self.user_widget)
        #self._ui.main_layout.addWidget(self.search_widget)
        self._ui.bottom_layout.addWidget(self.tab_view_widget)
        self._ui.bottom_layout.addWidget(self.app_bar_widget)

        # connect
        self.refresh_ui()
        self.title_bar_widget._ui.skin_btn.clicked.connect(self.pick_color)
        self.title_bar_widget._ui.reload_btn.clicked.connect(self.refresh_ui)
        self.user_widget.project_changed.connect(self.reset_project_engine)
        self.user_widget.partment_changed.connect(self.reset_step_engine)
        # self.setStyleSheet('QLabel{font:75 9pt \"Arial\";}')


    def refresh_ui(self):
        self.user_widget.clear_data()
        self.initialize_style()
        self.initialize_ui()
        self.initialize_project()
        self.reset_engine()

    def initialize_style(self):
        """
        初始化界面皮肤：优先获取用户本地数据
        Returns:
        """
        data_file = local_data.get_skin_data_path()
        if os.path.isfile(data_file):
            data = local_data.load_skin_data()
            self.skin_data['image'] = data.get('image', '')
            self.skin_data['color'] = QtGui.QColor(data['color'][0], data['color'][1], data['color'][2])
        self._set_style()

    def initialize_ui(self):
        """
        获取配置文件初始化界面
        Returns:
        """
        config_file = get_folder_path('config') + '/pipeline.yml'
        self.data = parse_yaml_file(config_file)
        for project in self.data:
            self.user_widget.add_project_item(project)

    def initialize_project(self):
        """
        初始化项目：优先获取用户本地数据
        Returns:
        """
        self.user_widget.clear_partment_item()
        data_file = local_data.get_project_data_path()
        if os.path.isfile(data_file):
            data = local_data.load_project_data()
            project = data.get('project')
            step = data.get('step')
            if project in self.data:
                if step in self.data.get(project):
                    project_index = self.user_widget.find_project(project)
                    self.user_widget.set_current_project(project_index)

                    for partment in self.data.get(project):
                        self.user_widget.add_partment_item(partment)

                    step_index = self.user_widget.find_partment(step)
                    self.user_widget.set_current_partment(step_index)
                    self.refresh_history_data()
                    self.set_project_icon(project)
                    return
        project = self.user_widget.current_project()
        for partment in self.data.get(project):
            self.user_widget.add_partment_item(partment)
        step = self.user_widget.current_partment()
        local_data.dump_project_data({'project':project, 'step':step})
        self.refresh_history_data()
        self.set_project_icon(project)

    def refresh_history_data(self):
        """
        更新本地数据
        Returns:
        """
        project = self.user_widget.current_project()
        partment = self.user_widget.current_partment()
        if project and partment:
            self.history_data[project] = partment

    def set_history_item(self):
        project = self.user_widget.current_project()
        step = self.history_data.get(project)
        if project and step:
            step_index = self.user_widget.find_partment(step)
            if step_index != -1:
                self.user_widget.set_current_partment(step_index)

    def set_project_icon(self, project):
        icon_path = get_folder_path('icons') + '/' + project + '.png'
        if not os.path.isfile(icon_path):
            icon_path = ':/icons/ver_logo.png'
        self.user_widget.set_project_icon(icon_path)

    def reset_project_engine(self):
        self._project = True
        project = self.user_widget.current_project()
        if not project:
            return
        self.user_widget.clear_partment_item()
        for partment in self.data.get(project):
            self.user_widget.add_partment_item(partment)
        self._project = False
        self.set_history_item()
        self.reset_engine()
        self.set_project_icon(project)

    def reset_step_engine(self, *arg):
        if not self._project:
            self.refresh_history_data()
        self.reset_engine()

    def reset_engine(self, *arg):
        self.tab_view_widget.clear_layout()
        project = self.user_widget.current_project()
        partment = self.user_widget.current_partment()
        if project and partment:
            data = self.data[project][partment]
            # 1.get data
            # 2.create group
            self.tab_view_widget.set_data(data)
            local_data.dump_project_data({'project':project, 'step':partment})

    def get_data(self):
        self.skin_data = {'image':'D:/gree.jpg', 'color':QtGui.QColor(0, 170, 230)}

    def pick_color(self):
        skin = SkinWidget(self)
        skin.show()

    def set_style(self):
        self._set_style()
        self.tab_view_widget.set_style(self.skin_data['color'])

    def _set_style(self):
        self.setStyleSheet('''
        *{border:none;font:75 9pt \"Arial\";}
        QFrame#main_frame{background-color:rgb(%s, %s, %s);}
        QFrame#top_frame{background-image:url(%s);}
        ''' % (self.skin_data['color'].red(), self.skin_data['color'].green(), self.skin_data['color'].blue(), self.skin_data['image']))




